package org.kl.bf.web.basic;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.kl.bf.entity.basic.BasicFile;
import org.kl.bf.entity.basic.NotifyContent;
import org.kl.bf.entity.basic.NotifyInfo;
import org.kl.bf.entity.easyui.EasyuiGrid;
import org.kl.bf.service.basic.BasicFileService;
import org.kl.bf.service.basic.NotifyInfoService;
import org.kl.bf.utils.BasicConstants;
import org.kl.bf.utils.KLServlets;
import org.kl.bf.web.base.BasicController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.MediaTypes;

/**
 * 
 * @Author hqm
 * @CreateTime 2014-3-13 下午9:34:36
 */
@Controller
@RequestMapping(value = "/basic/notifyInfo")
public class NotifyInfoController extends BasicController {
	@Autowired
	private NotifyInfoService notifyInfoService;

	@Autowired
	private BasicFileService basicFileService;

	@RequestMapping(value = "to_sended")
	public String toSended() {
		return "basic/notifyInfoSendedList";
	}

	/**
	 * 发件箱
	 * 
	 * @param pageNumber
	 * @param pageSize
	 * @param sortType
	 * @param orderType
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "sended_dataGrid", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String sendedDataGrid(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		searchParams.put("EQ_sender.id", BasicController.getCurrentUserId());
		searchParams.put("EQ_owner", BasicConstants.OWNER_SENDER + "");// 属于发送者
		searchParams.put("EQ_status", BasicConstants.STATUS_UNDELETE + "");// 未删除
		searchParams.put("LTE_attribute", BasicConstants.ATTRIBUTE_UNREAD + "");// 小于等于未读，即未读和已读的
		Page<NotifyInfo> notifyInfos = notifyInfoService.getUserNotifyInfo(searchParams, pageNumber, pageSize,
				sortType, orderType);
		setAllReceiversNameColor(notifyInfos, 5);
		EasyuiGrid grid = new EasyuiGrid();
		grid.setRows(notifyInfos.getContent());
		grid.setTotal((int) notifyInfos.getTotalElements());
		String result = jsonMapper.toJson(grid);
		return result;
	}

	/**
	 * 设置page中每条通知的所有接受者的颜色，接受者未读通知，名字颜色浅; 否则,加深。
	 * 
	 * @param page
	 * @param notifySize
	 *            操作page中通知的条数,为-1则全部更新
	 */
	private void setAllReceiversNameColor(Page<NotifyInfo> page, int notifySize) {
		if (page == null || page.getTotalElements() <= 0) {
			return;
		}
		StringBuilder sb;
		Map<String, Object> searchParams = new HashMap<String, Object>();
		for (NotifyInfo one : page.getContent()) {
			sb = new StringBuilder("");
			searchParams.put("EQ_pid", one.getId());
			Page<NotifyInfo> receives = notifyInfoService.getUserNotifyInfo(searchParams, 1, notifySize, "sendTime",
					"asc");
			if (receives == null || receives.getNumberOfElements() <= 0) {
				continue;
			}
			for (NotifyInfo ni : receives.getContent()) {
				if (ni.getId().equals(ni.getPid()) || ni.getReceiver() == null) {
					continue;
				}
				if (ni.getAttribute() == BasicConstants.ATTRIBUTE_UNREAD) {
					sb.append("<b>" + ni.getReceiver().getTrueName() + "</b>,");
				} else {
					sb.append(ni.getReceiver().getTrueName() + ",");
				}
			}
			if (sb.length() > 1) {
				if (receives.getNumberOfElements() > notifySize) {
					one.setColorRecerverName(sb.substring(0, sb.length() - 1) + "...");
				} else {
					one.setColorRecerverName(sb.substring(0, sb.length() - 1));
				}
			}
		}
	}

	@RequestMapping(value = "to_draft", method = RequestMethod.GET, produces = MediaTypes.JAVASCRIPT_UTF_8)
	public String toDraft() {
		return "basic/notifyInfoDraftList";
	}

	/**
	 * 草稿箱
	 * 
	 * @param pageNumber
	 * @param pageSize
	 * @param sortType
	 * @param orderType
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "draft_dataGrid", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String draftDataGrid(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		searchParams.put("EQ_sender.id", BasicController.getCurrentUserId());
		searchParams.put("EQ_owner", BasicConstants.OWNER_SENDER + "");// 属于发送者
		searchParams.put("EQ_status", BasicConstants.STATUS_UNDELETE + "");// 未删除
		searchParams.put("EQ_attribute", BasicConstants.ATTRIBUTE_DRAFT + "");// 草稿
		Page<NotifyInfo> notifyInfos = notifyInfoService.getUserNotifyInfo(searchParams, pageNumber, pageSize,
				sortType, orderType);
		EasyuiGrid grid = new EasyuiGrid();
		grid.setRows(notifyInfos.getContent());
		grid.setTotal((int) notifyInfos.getTotalElements());
		String result = jsonMapper.toJson(grid);
		return result;
	}

	@RequestMapping(value = "to_receiver", method = RequestMethod.GET, produces = MediaTypes.JAVASCRIPT_UTF_8)
	public String toReceiver() {
		return "basic/notifyInfoReceiverList";
	}

	/**
	 * 收件箱
	 * 
	 * @param pageNumber
	 * @param pageSize
	 * @param sortType
	 * @param orderType
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "receiver_dataGrid", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String receiverDataGrid(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		searchParams.put("EQ_receiver.id", BasicController.getCurrentUserId());
		searchParams.put("NEQ_owner", BasicConstants.OWNER_SENDER + "");// 不属于发送方，即是接收方，抄送方，密送方
		searchParams.put("EQ_status", BasicConstants.STATUS_UNDELETE + "");// 未删除
		searchParams.put("LTE_attribute", BasicConstants.ATTRIBUTE_UNREAD + "");// 小于等于未读，即未读和已读的
		Page<NotifyInfo> notifyInfos = notifyInfoService.getUserNotifyInfo(searchParams, pageNumber, pageSize,
				sortType, orderType);
		EasyuiGrid grid = new EasyuiGrid();
		grid.setRows(notifyInfos.getContent());
		grid.setTotal((int) notifyInfos.getTotalElements());
		String result = jsonMapper.toJson(grid);
		return result;
	}

	@RequestMapping(value = "to_recover", method = RequestMethod.GET, produces = MediaTypes.JAVASCRIPT_UTF_8)
	public String toRecover() {
		return "basic/notifyInfoRecoverList";
	}

	/**
	 * 回收箱
	 * 
	 * @param pageNumber
	 * @param pageSize
	 * @param sortType
	 * @param orderType
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "recover_dataGrid", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String recoverDataGrid(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		searchParams.put("EQ_receiver.id+OR+sender.id", BasicController.getCurrentUserId());
		searchParams.put("EQ_status", BasicConstants.STATUS_RECOVERABLE + "");// 回收
		Page<NotifyInfo> notifyInfos = notifyInfoService.getUserNotifyInfo(searchParams, pageNumber, pageSize,
				sortType, orderType);
		EasyuiGrid grid = new EasyuiGrid();
		grid.setRows(notifyInfos.getContent());
		grid.setTotal((int) notifyInfos.getTotalElements());
		String result = jsonMapper.toJson(grid);
		return result;
	}

	/**
	 * 查看邮件
	 * 
	 * @param id
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "detail/{id}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	public String detail(@PathVariable("id") String id, Model model) throws Exception {
		if (StringUtils.isBlank(id)) {
			model.addAttribute("error", "邮件唯一标识获取失败，无法查看，请刷新重试");
		} else {
			NotifyInfo entity = notifyInfoService.getNotifyInfoAndContentAndFiles(id);
			entity.setAttribute(BasicConstants.ATTRIBUTE_READ);
			notifyInfoService.saveNotifyInfo(entity);
			String fileId = entity.getJoinFileId();
			List<BasicFile> basicFileList = new ArrayList<BasicFile>();
			if (StringUtils.isNotBlank(fileId)) {
				basicFileList = basicFileService.getBasicFileByJoinFileId(fileId);
			}

			model.addAttribute("notifyInfo", entity);
			model.addAttribute("isSender",
					StringUtils.equals(BasicController.getCurrentUserId(), entity.getSender().getId()));
			model.addAttribute("basicFileList", basicFileList);
		}
		return "basic/notifyInfo-detail";
	}

	@RequestMapping(value = "create", produces = MediaTypes.JAVASCRIPT_UTF_8)
	public String create(@RequestParam(value = "id", defaultValue = "") String id,
			@RequestParam(value = "action", defaultValue = "") String action, Model model, ServletRequest request)
			throws Exception {
		if (StringUtils.isNotBlank(id)) {
			NotifyInfo notifyInfo = notifyInfoService.getNotifyInfoAndContentAndFiles(id);
			String joinFileId = notifyInfo.getJoinFileId();
			String fileId = notifyInfo.getJoinFileId();
			List<BasicFile> basicFileList = new ArrayList<BasicFile>();
			if (StringUtils.isNotBlank(fileId)) {
				basicFileList = basicFileService.getBasicFileByJoinFileId(fileId);
			}
			model.addAttribute("basicFileList", basicFileList);
			model.addAttribute("notifyInfo", notifyInfo);
			model.addAttribute("action", action);
			model.addAttribute("joinFileId", joinFileId);
		} else {
			NotifyInfo notifyInfo = new NotifyInfo();
			notifyInfo.setReceiversName((String) request.getAttribute("receiversName"));
			notifyInfo.setCcsName((String) request.getAttribute("ccsName"));
			notifyInfo.setBccsName((String) request.getAttribute("bccsName"));
			notifyInfo.setNotifyContent(new NotifyContent((String) request.getAttribute("content")));
			notifyInfo.setTitle((String) request.getAttribute("title"));
			model.addAttribute("notifyInfo", notifyInfo);
		}
		return "basic/notifyInfo-input";
	}

	// @RequiresPermissions("notifyInfo:update")
	@RequestMapping(value = "update", method = RequestMethod.POST)
	public String update(@Valid @ModelAttribute("notifyInfo") NotifyInfo notifyInfo,
			@RequestParam(value = "content", defaultValue = "") String content, Model model,
			RedirectAttributes redirectAttributes, HttpSession session) throws Exception {
		try {
			notifyInfoService.saveNotifyInfo(notifyInfo, content);
		} catch (Exception e) {
			e.printStackTrace();
			redirectAttributes.addFlashAttribute("receiversName", notifyInfo.getReceiversName());
			redirectAttributes.addFlashAttribute("ccsName", notifyInfo.getCcsName());
			redirectAttributes.addFlashAttribute("bccsName", notifyInfo.getBccsName());
			redirectAttributes.addFlashAttribute("content", content);
			redirectAttributes.addFlashAttribute("title", notifyInfo.getTitle());
			return "redirect:/basic/notifyInfo/create";
		}
		return "redirect:/basic/notifyInfo/to_sended";
	}

	/**
	 * 保存为草稿
	 * 
	 * @param notifyInfo
	 * @param receiversName
	 * @param content
	 * @param model
	 * @param redirectAttributes
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "saveDraft", method = RequestMethod.POST, produces = MediaTypes.JAVASCRIPT_UTF_8)
	public String saveDraft(@Valid @ModelAttribute("notifyInfo") NotifyInfo notifyInfo,
			@RequestParam(value = "content", defaultValue = "") String content, Model model,
			RedirectAttributes redirectAttributes, HttpSession session) throws Exception {
		try {
			notifyInfoService.saveDraft(notifyInfo, content);
		} catch (Exception e) {
			e.printStackTrace();
			redirectAttributes.addFlashAttribute("receiversName", notifyInfo.getReceiversName());
			redirectAttributes.addFlashAttribute("ccsName", notifyInfo.getCcsName());
			redirectAttributes.addFlashAttribute("bccsName", notifyInfo.getBccsName());
			redirectAttributes.addFlashAttribute("content", content);
			redirectAttributes.addFlashAttribute("title", notifyInfo.getTitle());
			return "redirect:/basic/notifyInfo/create";
		}
		return "redirect:/basic/notifyInfo/to_draft";
	}

	/**
	 * 回收邮件
	 * 
	 * @param id
	 * @param redirectAttributes
	 * @param session
	 * @return
	 */
	// @RequiresPermissions({ "notifyInfo:delete", "notifyInfo:update" })
	@RequestMapping(value = "recover/{id}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String recover(@PathVariable("id") String id, RedirectAttributes redirectAttributes, HttpSession session) {
		notifyInfoService.recoverNotifyInfo(id);
		return ajaxMsg("回收成功", true, null);
	}

	// 删除附件关联
	@RequestMapping(value = "delBasicFile", method = RequestMethod.GET, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String delBasicFile(@RequestParam(value = "joinFileId", defaultValue = "") String joinFileId,
			@RequestParam(value = "receiverId", defaultValue = "") String receiverId, RedirectAttributes redirectAttributes,
			HttpSession session) {
		try {
			notifyInfoService.deleteJoinFileId(joinFileId,receiverId);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("删除附件失败", true, null);
		}
		return ajaxMsg("删除附件成功", true, null);
	}

	/**
	 * 真正删除邮件
	 * 
	 * @param id
	 * @param redirectAttributes
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "delete/{id}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String delete(@PathVariable("id") String id, RedirectAttributes redirectAttributes, HttpSession session) {
		notifyInfoService.deleteNotifyInfo(id);
		return ajaxMsg("删除成功", true, null);
	}

	/**
	 * 我的未读收件条数
	 * 
	 * @return
	 */
	@RequestMapping(value = "receiverNotify-count", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String calendarCount() {
		long count = notifyInfoService.getCountNotReadReceiver(BasicController.getCurrentUserId());
		return ajaxMsg("我的未读收件条数获取成功", true, count);
	}

	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void getNotifyInfo(@RequestParam(value = "id", defaultValue = "-1") String id, Model model) {
		if (!id.equals("-1")) {
			model.addAttribute("notifyInfo", notifyInfoService.getNotifyInfo(id));
		}
	}
}
